<?php
define('ROOT',dirname( __FILE__ ));
require ROOT.'/phpmail/PHPMailerAutoload.php';
$config = require 'config.php';
function sendmail($to,$subjet,$content){
    global $config;
    $mail = new PHPMailer();
    $mail->IsSMTP();                  // send via SMTP
    $mail->Host = $config['smtp_host'];   // SMTP servers
    $mail->SMTPAuth = true;           // turn on SMTP authentication
    $mail->Username = $config['smtp_user'];     // SMTP username  注意：普通邮件认证不需要加 @域名
    $mail->Password = $config['smtp_pwd']; // SMTP password
    $mail->From = "admin@liuko.com";      // 发件人邮箱
    $mail->FromName =  "管理员";  // 发件人
    $mail->CharSet = "utf-8";   // 这里指定字符集！
    $mail->Encoding = "base64";
    $mail->AddAddress($to,"username");  // 收件人邮箱和姓名
    $mail->AddReplyTo("admin@liuko.com","liuko.com");
    $mail->IsHTML(true);  // send as HTML
    //邮件主题
    $mail->Subject = $subjet;
    //邮件内容
    $mail->Body = $content;
    $mail->AltBody ="text/html";
    if ($mail->Send()) return true;
    return false;
}

function main(){
    global $config;
    try{
        $redis = new Redis();
        $redis->connect($config['redis_host'],$config['redis_port']);
    }catch(Exception $e){
        die($e->getMessage());
    }
    while (true){
        while($task = $redis->lPop('mailtask')){
            echo "Get task!Start to send email\n";
            $task_data = json_decode($task,true);
            $mailto = $task_data['to'];
            $code = $task_data['code'];
            $nickname = $task_data['nickname'];
            $ip = $task_data['ip'];
            $datetime = date("Y-m-d H:i:s",$task_data['time']);
            $mailtpl = require 'mail.tpl.php';
            $reset_pwd_url = "http://localhost/?member&a=reset_pwd&code=".$code;
            $mail_content = sprintf($mailtpl,$nickname,$datetime,$ip,$reset_pwd_url,$reset_pwd_url);
            $ret = sendmail($mailto,'找回密码',$mail_content);
            if ($ret){
                echo 'send email to '.$mailto." success!\n";
            }else{
                echo 'send email to '.$mailto." fail!\n";
            }
        }
        echo date("Y-m-d H:i:s",time())." - status ok\n";
        sleep(5);
    }

}
main();

